﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using OutLook = Microsoft.Office.Interop.Outlook;

using Presenter;
using IView;
using DataTransferObject;

namespace JSKE
{
    /// <summary>
    ///Class xử lý các thông tin cấu hình hệ thống
    ///Chức năng: 
    /// 1. Cung cấp giao diện cho người dùng nhập thông tin cấu hình
    /// 2. Gọi presenter để lưu lại thông tin cấu hình vào file
    /// 3. Gọi presenter để tải lên lại thông tin cấu hình đã lưu trước đây
    ///Hiện thực các methods, properties của IOptionForm. Presenter muốn gọi thì thông qua các interface này.
    /// </summary>
    public partial class OptionForm : FormLang, IOptionForm
    {

        #region Attributes

        private PresenterOptionForm presenter;
        private SystemConfiguration systemConfig = SystemConfiguration.getInstance();
        private List<WorkingHourItem> _OptionFormWorkingHourList = new List<WorkingHourItem>();
        private WorkingHourItem currentWHI;
        private String pathToSave;

        #endregion

        #region Property

        public WorkingHourItem CurrentWHI
        {
            get
            {
                return currentWHI;
            }
            set
            {
                #region written by Ð.Khánh

                currentWHI = value;
                foreach (WorkingHoursBar item in whbArray)
                    item.DeleteAllBreaktime();

                chkScheduleTask.Checked = value.ScheduleTaskWhichHaveBeenAssignedInTheseHours;
                List<MappedFreeTimeBlock> listFTB = value.WorkTime.ListFreeTimeBlock;

                int start = 0, iFTB = 0;
                BKTimePoint startBreak = new BKTimePoint(0, 0);
                if (listFTB.Count > 0 && listFTB[0].Start == 0)
                {
                    start = listFTB[0].End;
                    iFTB = 1;
                    startBreak = new BKTimePoint(listFTB[0].EndDT);
                }

                int iWHB, endWHB;

                for (; iFTB < listFTB.Count; ++iFTB)
                {
                    iWHB = start / (24 * 60);
                    endWHB = (iWHB + 1) * (24 * 60);

                    while (endWHB < listFTB[iFTB].Start)
                    {
                        whbArray[iWHB++].AddBreak(startBreak, new BKTimePoint(24, 0));
                        startBreak = new BKTimePoint(0, 0);
                        endWHB += 24 * 60;
                    }

                    whbArray[iWHB].AddBreak(startBreak, new BKTimePoint(listFTB[iFTB].StartDT));

                    start = listFTB[iFTB].End;
                    startBreak = new BKTimePoint(listFTB[iFTB].EndDT);
                }

                iWHB = start / (24 * 60);

                if (iWHB != 7)
                {
                    endWHB = (iWHB + 1) * (24 * 60);

                    while (endWHB <= 24 * 60 * 7)
                    {
                        whbArray[iWHB++].AddBreak(startBreak, new BKTimePoint(24, 0));
                        startBreak = new BKTimePoint(0, 0);
                        endWHB += 24 * 60;
                    }
                }

                foreach (WorkingHoursBar whb in whbArray)
                    if (whb.IsOffDay) 
                        ((CheckBox)whb.Tag).Checked = false;
                    else
                        ((CheckBox)whb.Tag).Checked = true;

                #endregion

                #region backup cho một đống bùi nhùi, quá xịp, không thể chấp nhận. I don't know who fucking man can write like it!
                //currentWHI = value;
                //foreach (WorkingHoursBar item in whbarArray)
                //{
                //    item.DeleteAllBreaktime();
                //}

                //chkScheduleTask.Checked = value.ScheduleTaskWhichHaveBeenAssignedInTheseHours;

                //List<MappedFreeTimeBlock> listOfMappedFTBlock = value.WorkTime.ListFreeTimeBlock;
                //if (listOfMappedFTBlock.Count == 0) return;

                //List<MappedFreeTimeBlock> tempListMappedFTBlock = new List<MappedFreeTimeBlock>();

                //foreach (MappedFreeTimeBlock mappedFTBlock in listOfMappedFTBlock)
                //{
                //    tempListMappedFTBlock.AddRange(mappedFTBlock.SplitWithMaximumLenght(24 * 60));
                //}
                //listOfMappedFTBlock = tempListMappedFTBlock;

                //for (int i = 1; i <= whbarArray.Count(); i++)
                //{
                //    WorkingHoursBar currentWHBar = whbarArray[i - 1];
                //    List<MappedFreeTimeBlock> listOfMappedFTBlockOfCurrentBar = new List<MappedFreeTimeBlock>();

                //    #region Tìm ra các MappedFTBlock của ngày thứ trong tuần tương ứng với workinghourbar hiện tại
                //    foreach (MappedFreeTimeBlock mappedFTBlock in listOfMappedFTBlock)
                //    {
                //        if (mappedFTBlock.StartDT.Day < i)
                //        {
                //            continue;
                //        }
                //        else if (mappedFTBlock.StartDT.Day == i)
                //        // chú ý mappedFTBlock.StartDT.Day chỉ trong khỏang từ 1 đến 7 tương ứng với thứ 2 đến chủ nhật
                //        {
                //            listOfMappedFTBlockOfCurrentBar.Add(mappedFTBlock);
                //        }
                //        else
                //        {
                //            break;
                //        }
                //    }
                //    #endregion

                //    if (listOfMappedFTBlockOfCurrentBar.Count == 0)
                //    {
                //        currentWHBar.AddBreak(new BKTimePoint(0, 0), new BKTimePoint(24, 0));
                //        ((CheckBox)currentWHBar.Tag).Checked = false;

                //        continue;
                //    }
                //    List<BreakTime> listOfBreakTimeOfCurrentBar = new List<BreakTime>();
                //    #region Tạo các BreakTime cho WorkingHourBar hiện tại
                //    if (listOfMappedFTBlockOfCurrentBar.First().StartDT.Hour != 0 || listOfMappedFTBlockOfCurrentBar.First().StartDT.Minute != 0)
                //    {
                //        //currentWHBar.AddBreak(new BreakTime(DatetimeExt.CreateTimeInDay(0, 0)
                //        //    , DatetimeExt.CreateTimeInDay(listOfMappedFTBlockOfCurrentBar.First().StartDT.Hour, listOfMappedFTBlockOfCurrentBar.First().StartDT.Minute)
                //        //    ));

                //        //listOfBreakTimeOfCurrentBar.Add(new BreakTime(DatetimeExt.CreateTimeInDay(0, 0)
                //        //    , DatetimeExt.CreateTimeInDay(listOfMappedFTBlockOfCurrentBar.First().StartDT.Hour, listOfMappedFTBlockOfCurrentBar.First().StartDT.Minute)
                //        //    ));

                //        // Nếu freetimeblock đầu tiên không bắt đầu lúc 0h, thì add breaktime từ 0h -> trước freetimeblock này.
                //        BreakTime bk = new BreakTime(new BKTimePoint(0, 0), new BKTimePoint(listOfMappedFTBlockOfCurrentBar.First().StartDT));

                //        currentWHBar.AddBreak(bk);
                //        listOfBreakTimeOfCurrentBar.Add(bk);
                //    }
                //    for (int indexOfFTB = 0; indexOfFTB < listOfMappedFTBlockOfCurrentBar.Count - 1; indexOfFTB++)
                //    {
                //        MappedFreeTimeBlock currentMFTBlock = listOfMappedFTBlockOfCurrentBar[indexOfFTB];
                //        MappedFreeTimeBlock nextMFTBlock = listOfMappedFTBlockOfCurrentBar[indexOfFTB + 1];

                //        //BreakTime newBreakTime = new BreakTime(DatetimeExt.CreateTimeInDay(currentMFTBlock.EndDT.Hour, currentMFTBlock.EndDT.Minute)
                //        //    , DatetimeExt.CreateTimeInDay(nextMFTBlock.StartDT.Hour, nextMFTBlock.StartDT.Minute)
                //        //    );

                //        BreakTime newBreakTime = new BreakTime( new BKTimePoint(currentMFTBlock.EndDT),
                //                                                new BKTimePoint(nextMFTBlock.StartDT));

                //        listOfBreakTimeOfCurrentBar.Add(newBreakTime);
                //        currentWHBar.AddBreak(newBreakTime);
                //    }

                //    if (listOfMappedFTBlockOfCurrentBar.Last().EndDT.Hour != 0 || listOfMappedFTBlockOfCurrentBar.Last().EndDT.Minute != 0)
                //    {
                //        //listOfBreakTimeOfCurrentBar.Add(new BreakTime(DatetimeExt.CreateTimeInDay(listOfMappedFTBlockOfCurrentBar.Last().EndDT.Hour, listOfMappedFTBlockOfCurrentBar.Last().EndDT.Minute)
                //        //    , DatetimeExt.CreateTimeInDay(23, 59)
                //        //    ));
                //        //currentWHBar.AddBreak(new BreakTime(DatetimeExt.CreateTimeInDay(listOfMappedFTBlockOfCurrentBar.Last().EndDT.Hour, listOfMappedFTBlockOfCurrentBar.Last().EndDT.Minute)
                //        //    , DatetimeExt.CreateTimeInDay(23, 59)
                //        //    ));

                //        BreakTime newBreakTime = new BreakTime( new BKTimePoint(listOfMappedFTBlockOfCurrentBar.Last().EndDT),
                //                                                new BKTimePoint(24, 0));

                //        listOfBreakTimeOfCurrentBar.Add(newBreakTime);
                //        currentWHBar.AddBreak(newBreakTime);
                //    }
                //    #endregion

                //}

                //foreach (WorkingHoursBar whBar in whbarArray)
                //{
                //    whBar.ReloadDateTimePicker();
                //}
                #endregion
            }
        }

        #endregion

        #region Constructor

        /// <summary>
        /// Initializes a new instance of the <see cref="OptionForm"/> class.
        /// </summary>
        WorkingHoursBar[] whbArray;
        CheckBox[] chkWeekDay;
        public OptionForm()
        {
            //InitializeComponent();

            whbArray = new WorkingHoursBar[7];
            chkWeekDay = new CheckBox[7];

            chkMon.Tag = whbArray[0] = workingHoursBar1;
            chkTue.Tag = whbArray[1] = workingHoursBar2;
            chkWed.Tag = whbArray[2] = workingHoursBar3;
            chkThu.Tag = whbArray[3] = workingHoursBar4;
            chkFri.Tag = whbArray[4] = workingHoursBar5;
            chkSat.Tag = whbArray[5] = workingHoursBar6;
            chkSun.Tag = whbArray[6] = workingHoursBar7;

            chkWeekDay[0] = chkMon;
            chkWeekDay[1] = chkTue;
            chkWeekDay[2] = chkWed;
            chkWeekDay[3] = chkThu;
            chkWeekDay[4] = chkFri;
            chkWeekDay[5] = chkSat;
            chkWeekDay[6] = chkSun;

            for (int i = 0; i < 7; ++i)
                whbArray[i].Tag = chkWeekDay[i];

            pathToSave = Application.StartupPath + @"\JSKEData.bin";

            // khởi tạo presenter để xử lý
            presenter = new PresenterOptionForm(this, DATA_MODE);
            presenter.LoadSettingFromFile();
        }

        #endregion

        #region IOptionForm Members

        public String PathToSave
        {
            get { return this.pathToSave; }
            set { this.pathToSave = value; }
        }
        /// <summary>
        /// Loads the setting.
        /// đọc object systemConfiguration và đưa vào giao diện của Option
        /// </summary>
        /// <param name="systemConfiguration">The system configuration.</param>
        /// <returns></returns>
        public void LoadSetting(SystemConfiguration systemConfiguration)
        {
            if (systemConfiguration.TabWorkingHoursData.ListOfWorkingHourItems.Count == 0)
            {
                return;
            }
            int i;
            #region tabTask
            // for tab Task
            if (systemConfiguration == null)
            {
                return;
            }

            //if (systemConfiguration.IsSimpleModeOrAdvanceMode == 1)
            //{
            //    btnAdvancedOptioin.Text = "Simple Mode";
            //}
            //else
            //{
            //    btnAdvancedOptioin.Text = "Advance Mode";
            //}

            if (systemConfiguration.TabTaskData.DefaultToCurrentDateTime == true)
            {
                chkDefaultCurrentDate.Checked = true;
            }
            else
            {
                chkDefaultCurrentDate.Checked = false;
            }

            cbOrderBy.SelectedIndex = systemConfiguration.TabTaskData.OrderBy;
            cbSort.SelectedIndex = systemConfiguration.TabTaskData.OrderByType;

            cbThenby1.SelectedIndex = systemConfiguration.TabTaskData.AndThenBy;
            cbSort1.SelectedIndex = systemConfiguration.TabTaskData.AndThenByType;

            cbThenBy2.SelectedIndex = systemConfiguration.TabTaskData.AndThenThenBy;
            cbSort2.SelectedIndex = systemConfiguration.TabTaskData.AndThenThenByType;

            //lblScheduleTaskIn.Text = "Schedule task in ..." + systemConfiguration.TabTaskData.ScheduleTheTaskIn;
            ////systemConfiguration.TabTaskData.ScheduleTheTaskIn = "se them vao luc sau";


            //chMoveCompletedTaskTo.Checked = systemConfiguration.TabTaskData.CheckboxMoveCompletedTaskTo;

            //chDeleteCompletedOccouranceOfTask.Checked
            //= systemConfiguration.TabTaskData.DeleteCompletedOccourancesOfReccuringTasks;

            #endregion

            #region Tab Project
            //for tab project



            int numOfProject = systemConfiguration.TabProjectData.ListProjectName.Count;
            chklbProject.Items.Clear();
            for (i = 0; i < numOfProject; i++)
            {
                chklbProject.Items.Add(systemConfiguration.TabProjectData.ListProjectName[i].ToString());
            }


            #endregion

            #region Tab Calendar
            //for tab Calendar
            //chkMarkPrivate.Checked = systemConfiguration.TabCalendarData.MarkAllAsPrivate;

            //chkNotStarted.Checked = systemConfiguration.TabCalendarData.CreateForTaskThatAreNotStartedOrInProgress;


            //chkKeeprecord.Checked = systemConfiguration.TabCalendarData.KeepARecordOfCompletedWork;
            //chkCreateAllday.Checked = systemConfiguration.TabCalendarData.CreateAllDayEventForMileStone;

            //chkMarkPrivate.Checked = systemConfiguration.TabCalendarData.MarkAllAsPrivate;

            //ddlShowAs.SelectedIndex = systemConfiguration.TabCalendarData.ShowAsSelectedItem;

            //ddlShowTimeAs.SelectedIndex = systemConfiguration.TabCalendarData.ShowTimeAsSelectedItem;



            txtBefore.Text = systemConfiguration.TabCalendarData.BeforeDefaultAllowces;
            txtAfter.Text = systemConfiguration.TabCalendarData.AfterDefaultAllowces;

            //lblSelectedAppPath.Text = systemConfiguration.TabCalendarData.MyAppointmenFolderPath;
            //lblWriteTaskEntriesTo.Text = "Write task entries to " + systemConfiguration.TabCalendarData.WriteTaskEntriesToPath;


            #endregion

            #region Tab Working Hour

            systemConfig = systemConfiguration;
            cbWorkingHours.Items.AddRange(systemConfig.TabWorkingHoursData.ListOfWorkingHourItems.ToArray());

            #region Load CurrentWorkingHourItem
            // sự kiện cbWorkingHours_SelectedIndexChanged sẽ thực hiện việc load WorkingHour từ file đã được serialize
            int currentSelectedWHID = systemConfig.TabWorkingHoursData.CurrentSelectedWorkingHourID;
            cbWorkingHours.SelectedIndex = currentSelectedWHID;
            #endregion
            //CurrentWHI = systemConfig.TabWorkingHoursData.ListOfWorkingHourItems[cbWorkingHours.SelectedIndex];
            CurrentWHI = systemConfig.TabWorkingHoursData.ListOfWorkingHourItems[systemConfig.TabWorkingHoursData.CurrentSelectedWorkingHourID];


            #endregion

            #region Tab Option
            // for tab option

            //chkTaskStartDueDates.Checked = systemConfiguration.TabOptionData.TaskShoudSetStartAndDueToTheScheduleDates;



            int numberOfRestoreOrig = systemConfiguration.TabOptionData.RestoreMyOriginalStartAndDate.Count;
            //ddlInitialTab.Items.Clear();
            //for (i = 0; i < numberOfRestoreOrig; i++)
            //{
            //    ddlInitialTab.Items.Add(systemConfiguration.TabOptionData.RestoreMyOriginalStartAndDate[i].ToString());
            //}

            //ddlInitialTab.SelectedIndex = systemConfiguration.TabOptionData.SelectedRestoreMyOrig;

            //txtPrefixTastMissed.Text = systemConfiguration.TabOptionData.IfTaskConstraintIsMissedPrefixTaskSubject;

            //txtDefaultMinimumSplit.Text = systemConfiguration.TabOptionData.DefaultMinimumTaskSplit;

            //chkShowSumary.Checked = systemConfiguration.TabOptionData.ShowSumamaryWhenTaskRescheduleIsComplete;
            #endregion

            return;
        }

        /// <summary>
        /// Creates the configuration obj.
        /// tạo 1 object dạng SystemConfiguration
        /// đọc các thông tin từ main form vào
        /// ghi thông tin vào trong object,trả kết quả về cho result
        /// </summary>
        /// <param name="systemConfiguration">The system configuration.</param>
        /// <returns></returns>
        public bool CreateConfigurationObj(ref SystemConfiguration systemConfiguration)
        {
            #region tabTask
            // for tab Task
            systemConfiguration.IsSimpleModeOrAdvanceMode = 1; // se chinh sua lai sau

            systemConfiguration.TabTaskData.DefaultToCurrentDateTime
                = chkDefaultCurrentDate.Checked;

            systemConfiguration.TabTaskData.OrderBy = cbOrderBy.SelectedIndex;
            systemConfiguration.TabTaskData.OrderByType = cbSort.SelectedIndex;

            systemConfiguration.TabTaskData.AndThenBy = cbThenby1.SelectedIndex;
            systemConfiguration.TabTaskData.AndThenByType = cbSort1.SelectedIndex;

            systemConfiguration.TabTaskData.AndThenThenBy = cbThenBy2.SelectedIndex;
            systemConfiguration.TabTaskData.AndThenThenByType = cbSort2.SelectedIndex;

            systemConfiguration.TabTaskData.ScheduleTheTaskIn = "se them vao luc sau";

            //systemConfiguration.TabTaskData.CheckboxMoveCompletedTaskTo
            //    = chMoveCompletedTaskTo.Checked;
            //systemConfiguration.TabTaskData.DeleteCompletedOccourancesOfReccuringTasks
            //    = chDeleteCompletedOccouranceOfTask.Checked;

            #endregion

            #region Tab Project
            //for tab project

            systemConfiguration.TabProjectData.ListProjectName.Clear();
            for (int numInchkl = 0; numInchkl < chklbProject.Items.Count; numInchkl++)
            {
                systemConfiguration.TabProjectData.ListProjectName.Add(chklbProject.Items[numInchkl].ToString());
            }

            #endregion

            #region Tab Calendar
            //for tab Calendar
            //systemConfiguration.TabCalendarData.MarkAllAsPrivate = chkMarkPrivate.Checked;

            //systemConfiguration.TabCalendarData.CreateForTaskThatAreNotStartedOrInProgress
            //    = chkNotStarted.Checked;
            //systemConfiguration.TabCalendarData.KeepARecordOfCompletedWork
            //    = chkKeeprecord.Checked;
            //systemConfiguration.TabCalendarData.CreateAllDayEventForMileStone
            //    = chkCreateAllday.Checked;
            //systemConfiguration.TabCalendarData.MarkAllAsPrivate
            //    = chkMarkPrivate.Checked;
            //systemConfiguration.TabCalendarData.ShowAsSelectedItem
            //    = ddlShowAs.SelectedIndex;
            //systemConfiguration.TabCalendarData.ShowTimeAsSelectedItem
            //    = ddlShowTimeAs.SelectedIndex;

            systemConfiguration.TabCalendarData.BeforeDefaultAllowces
                = txtBefore.Text.ToString();
            systemConfiguration.TabCalendarData.AfterDefaultAllowces
                = txtAfter.Text.ToString();
            #endregion

            #region Tab Working Hour

            // for tab Workng Hour

            //kiem tra xem lan apply nay co thay doi default working hour ID khong
            systemConfiguration.TabWorkingHoursData.CurrentSelectedWorkingHourID = cbWorkingHours.SelectedIndex;
            systemConfiguration.TabWorkingHoursData = systemConfig.TabWorkingHoursData;


            #endregion

            #region Tab Option
            // for tab option
            //systemConfiguration.TabOptionData.TaskShoudSetStartAndDueToTheScheduleDates
            //    = chkTaskStartDueDates.Checked;

            //systemConfiguration.TabOptionData.RestoreMyOriginalStartAndDate.Clear();

            //for (i = 0; i < ddlInitialTab.Items.Count; i++)
            //{
            //    systemConfiguration.TabOptionData.RestoreMyOriginalStartAndDate.Add(ddlInitialTab.Items[i].ToString());
            //}
            //systemConfiguration.TabOptionData.SelectedRestoreMyOrig = ddlInitialTab.SelectedIndex;
            //systemConfiguration.TabOptionData.IfTaskConstraintIsMissedPrefixTaskSubject
            //    = txtPrefixTastMissed.Text.ToString();
            //systemConfiguration.TabOptionData.DefaultMinimumTaskSplit
            //    = txtDefaultMinimumSplit.Text.ToString();
            //systemConfiguration.TabOptionData.ShowSumamaryWhenTaskRescheduleIsComplete
            //    = chkShowSumary.Checked;
            #endregion

            return true;
        }

        #endregion

        WorkingHoursBar currentWHB;
        private void UpdateWorkingHour()
        {
            #region written by Ð.Khánh

            MappedFreeTimeList mappedFTList = new MappedFreeTimeList();
            int start = 0;

            for (int iWHB = 0; iWHB < 7; ++iWHB)
            {
                List<BreakTime> listBK = whbArray[iWHB].GetBreaktimeList();

                int iBK = 0;
                if (listBK.Count > 0 && listBK[0].IsFirstBreakOfDay() && start == iWHB * 24 * 60)
                {
                    start = listBK[0].End.ToMinute + iWHB * 24 * 60;
                    iBK = 1;
                }

                for (; iBK < listBK.Count; ++iBK)
                {
                    mappedFTList.Add(new MappedFreeTimeBlock(start, listBK[iBK].Start.ToMinute + iWHB * 24 * 60));
                    start = listBK[iBK].End.ToMinute + iWHB * 24 * 60;
                }
            }

            if (start < 24 * 60 * 7)
                mappedFTList.Add(new MappedFreeTimeBlock(start, 24 * 60 * 7));

            #endregion

            #region Tạo MappedFreeTimeList tương ứng với working hour. Đứa nào viết mà xịp vậy, như đám rừng.

            //for (int currentDayOfWeek = 0; currentDayOfWeek < whbArray.Count(); ++currentDayOfWeek)
            //{
            //    if (whbArray[currentDayOfWeek].Enabled)
            //    {
            //        int startOfCurrentDay = currentDayOfWeek * 24 * 60;
            //        List<BreakTime> listBreakTimeOfCurDay = whbArray[currentDayOfWeek].GetBreaktimeList().ToList();
            //        if (listBreakTimeOfCurDay.Count == 0)
            //        {
            //            MappedFreeTimeBlock newMappedFTB = new MappedFreeTimeBlock(startOfCurrentDay, startOfCurrentDay + 24 * 60);
            //            mappedFTList.AddMappedFreeTimeBlock(newMappedFTB);
            //        }
            //        else if (listBreakTimeOfCurDay.Count == 1)
            //        {
            //            BreakTime breakTime = listBreakTimeOfCurDay[0];
            //            if (breakTime.IsFirstBreakOfDay())
            //            {
            //                mappedFTList.AddMappedFreeTimeBlock(new MappedFreeTimeBlock(breakTime.GetMappedEndTime(startOfCurrentDay), (currentDayOfWeek + 1) * 24 * 60));
            //            }
            //            else if (breakTime.IsEndBreakOfDay())
            //            {
            //                mappedFTList.AddMappedFreeTimeBlock(new MappedFreeTimeBlock(startOfCurrentDay, (breakTime.GetMappedStartTime(startOfCurrentDay))));
            //            }
            //            else
            //            {
            //                mappedFTList.AddMappedFreeTimeBlock(new MappedFreeTimeBlock(startOfCurrentDay, breakTime.GetMappedStartTime(startOfCurrentDay)));
            //                mappedFTList.AddMappedFreeTimeBlock(new MappedFreeTimeBlock(breakTime.GetMappedEndTime(startOfCurrentDay), (currentDayOfWeek + 1) * 24 * 60));
            //            }
            //        }
            //        else
            //        {
            //            BreakTime firstBreakTime = listBreakTimeOfCurDay.First();
            //            int startOfNewFTBlock = startOfCurrentDay;
            //            if (firstBreakTime.IsFirstBreakOfDay())
            //            {
            //                // nếu BreakTime đầu tiên bắ đầu lúc 12:00 AM thì MappedFreeTimeBlock đầu tiên bắt đầu tại
            //                // End của BreakTime đó
            //                startOfNewFTBlock = firstBreakTime.GetMappedEndTime(startOfCurrentDay);
            //            }

            //            for (int i = 0; i < listBreakTimeOfCurDay.Count; i++)
            //            {
            //                BreakTime currentBreakTime = listBreakTimeOfCurDay[i];

            //                if (currentBreakTime.GetMappedEndTime(startOfCurrentDay) <= startOfNewFTBlock)
            //                {
            //                    // bỏ qua BreakTime đầu tiên của ngày, nếu ngày bắt đầu sau 12:00 AM
            //                    continue;
            //                }
            //                mappedFTList.AddMappedFreeTimeBlock(new MappedFreeTimeBlock(startOfNewFTBlock, currentBreakTime.GetMappedStartTime(startOfCurrentDay)));
            //                startOfNewFTBlock = currentBreakTime.GetMappedEndTime(startOfCurrentDay);
            //            }

            //            BreakTime lastBreakTime = listBreakTimeOfCurDay.Last();
            //            if (!lastBreakTime.IsEndBreakOfDay())
            //            {
            //                mappedFTList.AddMappedFreeTimeBlock(new MappedFreeTimeBlock(lastBreakTime.GetMappedEndTime(startOfCurrentDay), startOfCurrentDay + 60 * 24));
            //            }
            //        }
            //    }
            //}
            #endregion

            currentWHI.WorkTime = mappedFTList;

        }

        #region Events of controls

        /// <summary>
        /// Handles the Click event of the btnOK control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void btnOK_Click(object sender, EventArgs e)
        {
            UpdateWorkingHour();
            presenter.SaveConfigurationToFile();
            this.Close();
        }

        /// <summary>
        /// Handles the Click event of the btnCancel control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// Handles the Click event of the btnApply control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void btnApply_Click(object sender, EventArgs e)
        {
            UpdateWorkingHour();
            presenter.SaveConfigurationToFile();
        }

        private void btnInsertNewProject_Click(object sender, EventArgs e)
        {
            if (txtInsertNewProject.Text != "")
            {
                chklbProject.Items.Add(txtInsertNewProject.Text.ToString());
                txtInsertNewProject.Clear();
            }
        }

        private void btnDeleteProject_Click(object sender, EventArgs e)
        {
            chklbProject.Items.Remove(chklbProject.SelectedItem);
        }

        private void optDefaultHours_CheckedChanged(object sender, EventArgs e)
        {
            //_defaultWorkingHour = ddlWorkingHours.SelectedIndex;
        }

        private void btnAddBreaktime_Click(object sender, EventArgs e)
        {
            if (currentWHB == null)
            {
                MessageBox.Show("You must choose a Working hours bar!");
                return;
            }

            BreaktimeDlg dlg = new BreaktimeDlg();
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    currentWHB.AddBreak(dlg.BreaktimeValue);
                }
                catch (BreaktimeException ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void workingHoursBar7_OnFocus(WorkingHoursBar whb)
        {
            currentWHB = whb;
            btnDeleteBreaktime.Enabled = btnModifyBreaktime.Enabled = currentWHB.CurrentBreaktime != null;
        }

        private void btnDeleteBreaktime_Click(object sender, EventArgs e)
        {
            if (currentWHB == null)
            {
                MessageBox.Show("You must choose a Working hours!");
                return;
            }

            currentWHB.DeleteActive();
        }

        private void ModifyBreaktime_Click(object sender, EventArgs e)
        {
            if (currentWHB == null)
            {
                MessageBox.Show("You must choose a Working hours!");
                return;
            }

            BreaktimeDlg dlg = new BreaktimeDlg(currentWHB.CurrentBreaktime);

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    currentWHB.ModifyActive(dlg.BreaktimeValue);
                }
                catch (BreaktimeException ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

        }

        private void workingHoursBar7_OnCurrentBreaktimeChange(WorkingHoursBar whb)
        {
            btnDeleteBreaktime.Enabled = btnModifyBreaktime.Enabled = whb.CurrentBreaktime != null;
            if (whb.CurrentBreaktime != null)
            {
                dtpBkStart.Value = whb.CurrentBreaktime.Start.ToDateTime;
                dtpBkEnd.Value = whb.CurrentBreaktime.End.ToDateTime;
            }
        }

        IEnumerable<BreakTime> copy;
        private void btnCopy_Click(object sender, EventArgs e)
        {
            copy = currentWHB.GetBreaktimeList();
        }

        private void btnPaste_Click(object sender, EventArgs e)
        {
            if (copy == null)
            {
                MessageBox.Show("You havent copy!");
                return;
            }
            currentWHB.DeleteAllBreaktime();
            foreach (BreakTime bt in copy)
            {
                currentWHB.AddBreak(bt);
            }
        }

        private void chkSat_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox chk = sender as CheckBox;
            ((WorkingHoursBar)chk.Tag).IsOffDay = chk.Checked;
        }

        #endregion

        #region Other Event Handlers

        private void btnNewWH_Click(object sender, EventArgs e)
        {
            NewWHDlg dlg = new NewWHDlg(systemConfig.TabWorkingHoursData.ListOfWorkingHourItems);

            if (DialogResult.OK == dlg.ShowDialog())
            {
                currentWHI = dlg.WHI;
                systemConfig.TabWorkingHoursData.ListOfWorkingHourItems.Add(currentWHI);
                cbWorkingHours.Items.Clear();
                cbWorkingHours.Items.AddRange(systemConfig.TabWorkingHoursData.ListOfWorkingHourItems.ToArray());
                cbWorkingHours.SelectedIndex = cbWorkingHours.Items.Count - 1;
            }


            //currentSysConfig.TabWorkingHoursData.AddWorkingHourItem
        }

        private void cbWorkingHours_SelectedIndexChanged(object sender, EventArgs e)
        {
            //CurrentWHI = cbWorkingHours.SelectedItem as WorkingHourItem;
            CurrentWHI = systemConfig.TabWorkingHoursData.ListOfWorkingHourItems[cbWorkingHours.SelectedIndex];
        }

        private void OptionForm_Load(object sender, EventArgs e)
        {
        }

        private void butSelectAppFolder_Click(object sender, EventArgs e)
        {
            try
            {
                OutLook._Application olts = new OutLook.Application();
                //Lấy thư mục default
                //OutLook.MAPIFolder fldCal = (OutLook.MAPIFolder)outlookObj.Session.GetDefaultFolder(OutLook.OlDefaultFolders.olFolderCalendar);
                MainForm.OUTLOOK_FOLDER_CAL = (OutLook.MAPIFolder)olts.Session.PickFolder();
                systemConfig.TabCalendarData.MyAppointmenFolderPath = MainForm.OUTLOOK_FOLDER_CAL.FolderPath;
                this.lblSelectedAppPath.Text = systemConfig.TabCalendarData.MyAppointmenFolderPath;
            }
            catch (Exception ex)
            {
                MessageBox.Show("You must choose the right Calendar folder: " + ex.Message, "Important Note", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }

        }
        #endregion

        private void btnDelete_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Unimplemented feature!");
        }

    }
}